#!/usr/bin/env perl
use strict;
use warnings;

use FindBin ();
use lib "$FindBin::Bin/../lib";

use Mojolicious;
use Mojo::Server::Daemon;
use Textstat::Contract;

# One handler for every route: Textstat::Contract->route decides the status code
# and the body, so this file only moves bytes and binds the port.
my $handle = sub {
    my $c = shift;

    my $reply = Textstat::Contract->route(
        $c->req->method,
        $c->req->url->path->to_string,
        $c->req->url->query->to_string,
        $c->req->body,
    );

    $c->res->headers->content_type('application/json');
    return $c->render(data => $reply->{body}, status => $reply->{status});
};

my $app = Mojolicious->new;
$app->log->level('error');
$app->routes->any('/' => $handle);
$app->routes->any('/*rest' => $handle);

my $port = $ENV{PORT} || 8080;
Mojo::Server::Daemon->new(app => $app, listen => ["http://127.0.0.1:$port"])->run;
